<template>
  <lb-layout
    class="app-container energyCoal"
    v-loading="$store.getters.loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="#a19f9fb0;"
    :paddBottom="5"
  >
    <!-- <lb-layout> -->
    <!-- 查询 or 新增 or 编辑-->
    <el-row>
      <el-col :span="21">
        <el-form
          :model="queryParams"
          ref="queryForm"
          size="small"
          :inline="true"
        >
          <el-form-item label="预警等级:" prop="level">
            <el-select
              size="small"
              v-model="queryParams.level"
              placeholder="请选择"
              :disabled="!editFlage || !addFlage"
            >
              <el-option
                v-for="(item, index) in dict.type.warnning_level"
                :key="index"
                :label="item.label"
                :value="Number(item.value)"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="预警规则版本号:" prop="version">
            <el-select
              size="small"
              v-model="queryParams.version"
              placeholder="请选择"
              :disabled="!editFlage || !addFlage"
              @change="getList"
            >
              <el-option
                v-for="(item, index) in versionsArr"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              icon="el-icon-search"
              size="small"
              @click="handleQuery"
              v-show="addFlage && editFlage"
              v-hasPermi="['energy:manage:list']"
            >
              搜索
            </el-button>
            <el-button
              icon="el-icon-refresh"
              size="small"
              @click="handleresetQuery"
              v-show="addFlage && editFlage"
              v-hasPermi="['energy:manage:list']"
            >
              重置
            </el-button>
            <el-button
              icon="el-icon-edit"
              size="small"
              type="primary"
              v-show="addFlage && publishStatus != 2 && editFlage"
              @click="handleEdit"
              v-hasPermi="['energy:manage:edit']"
            >
              编辑
            </el-button>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="3" class="button-area-ex">
        <el-button
          :type="addFlage ? 'text' : 'primary'"
          size="small"
          :plain="addFlage"
          icon="el-icon-plus"
          :disabled="!editFlage"
          v-show="editFlage"
          @click="handleAdd"
          v-hasPermi="['energy:manage:edit']"
        >
          {{ addFlage ? "新增版本" : "确认" }}
        </el-button>
        <el-button
          icon="el-icon-check"
          size="small"
          type="primary"
          :disabled="!addFlage"
          v-show="!editFlage"
          @click="handleEdit"
          v-hasPermi="['energy:manage:edit']"
        >
          保存
        </el-button>
        <el-button
          type="primary"
          v-show="!addFlage || !editFlage"
          plain
          size="small"
          @click="handleCancel"
        >
          取消
        </el-button>
        <el-button
          type="text"
          v-show="publishStatus === 0 && addFlage && editFlage"
          size="small"
          icon="el-icon-upload2"
          @click="handleConfirm"
        >
          公式确认
        </el-button>
        <el-button
          type="text"
          v-show="publishStatus === 1 && addFlage && editFlage"
          size="small"
          icon="el-icon-upload2"
          @click="handlePublish"
        >
          发布
        </el-button>
      </el-col>
    </el-row>
    <div class="table-area">
      <!-- 表格标题 -->
      <!-- <div class="table-title">
        <Title name="能耗预警规则" :line="false"></Title>
      </div> -->
      <!-- 表格 -->
      <el-form
        :model="listform"
        ref="tableForm"
        :rules="listRules"
        :inline="true"
      >
        <el-table :data="listform.list" border style="width: 100%" height="630">
          <!-- show-summary 合计 -->
          <el-table-column
            prop="level"
            label="预警等级"
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'list.' + scope.$index + '.level'"
                :rules="listRules.level"
                v-show="!inputFlage"
              >
                <el-select
                  size="small"
                  v-model="scope.row.level"
                  placeholder="预警等级"
                  :disabled="inputFlage"
                  class="cell-center"
                  @change="
                    (val) => {
                      changeRules(scope.$index);
                    }
                  "
                >
                  <el-option
                    v-for="(item, index) in dict.type.warnning_level"
                    :key="index"
                    :label="item.label"
                    :value="Number(item.value)"
                  />
                </el-select>
              </el-form-item>
              <dict-tag
                class="type-tag"
                v-show="inputFlage"
                :options="dict.type.warnning_level"
                :value="scope.row.level + ''"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="instructType"
            label="能源种类"
            align="center"
            width="200"
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'list.' + scope.$index + '.instructType'"
                :rules="listRules.instructType"
                v-show="!inputFlage"
              >
                <el-select
                  class="cell-center"
                  size="small"
                  v-model="scope.row.instructType"
                  :disabled="inputFlage"
                  style="width: 100%"
                  @change="
                    (val) => {
                      getContent(val, scope.$index);
                    }
                  "
                >
                  <el-option
                    v-for="(item, index) in dict.type.warning_instruct_type"
                    :key="index"
                    :label="item.label"
                    :value="Number(item.value)"
                  ></el-option>
                </el-select>
              </el-form-item>
              <dict-tag
                class="type-tag"
                v-show="inputFlage"
                :options="dict.type.warning_instruct_type"
                :value="scope.row.instructType + ''"
              />
            </template>
          </el-table-column>
          <el-table-column
            prop="templateId"
            label="预警规则描述"
            min-width="280"
            align="center"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-form-item
                :prop="'list.' + scope.$index + '.templateId'"
                :rules="listRules.templateId"
                v-show="!inputFlage"
              >
                <el-select
                  class="cell-center"
                  size="small"
                  v-model="scope.row.templateId"
                  :disabled="inputFlage"
                  style="width: 100%"
                  @change="
                    (val) => {
                      getVal(val, scope.row.instructVoTemplates, scope.$index);
                    }
                  "
                >
                  <el-option
                    v-for="(item, index) in scope.row.instructVoTemplates"
                    :key="index"
                    :label="item.content"
                    :value="Number(item.templateId)"
                    :disabled="item.disabled"
                  ></el-option>
                </el-select>
              </el-form-item>
              <div v-show="inputFlage">
                {{ scope.row.content }}
              </div>
            </template>
          </el-table-column>
          <el-table-column label="规则预警值" align="center" min-width="200">
            <template slot-scope="scope">
              <el-form-item
                v-show="!inputFlage"
                v-for="(item, index) in scope.row.numList"
                :key="index"
              >
                <el-input
                  size="small"
                  v-model="item.x"
                  :disabled="inputFlage"
                  :placeholder="'规则预警值' + index"
                  class="cell-center"
                  @input="
                    (val) => {
                      replaceDigitDeal(val, 2, scope.$index, 'numList', index);
                    }
                  "
                >
                </el-input>
              </el-form-item>
              <div v-show="inputFlage">
                {{ scope.row.paramsStr }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="100"
            v-if="!inputFlage"
            class-name="small-padding fixed-width"
          >
            <template slot-scope="scope">
              <el-button
                size="small"
                type="text"
                icon="el-icon-delete"
                class="text-danger"
                @click="handleDelete(scope.row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>

      <!-- 增行按钮 -->
      <div class="addbutton-area" v-show="!addFlage || !editFlage">
        <div class="midbutton">
          <el-button
            type="text"
            size="small"
            icon="el-icon-plus"
            @click="addRow"
          >
            新增一行
          </el-button>
        </div>
      </div>
      <el-row
        v-show="addFlage"
        style="
          background-color: #f2f2f5;
          padding: 10px;
          padding-top: 20px;
          padding-bottom: 0px;
          margin-top: 20px;
        "
      >
        <el-col class="midcol" :span="12">
          <span>
            <span style="font-size: 16px; color: #606266; font-weight: bold"
              >发布时间：</span
            >
            {{ publishTime }}
          </span>
        </el-col>
        <el-col class="midcol" :span="12">
          <span>
            <span style="font-size: 16px; color: #606266; font-weight: bold"
              >失效时间：</span
            >
            {{ expirationTime || "暂无失效时间" }}
          </span>
        </el-col>
      </el-row>
    </div>

    <!-- </lb-layout> -->
  </lb-layout>
</template>
lb-layout
<script>
import {
  listversion,
  list,
  instructList,
  addWarningEmanage,
  auditGoPublish,
  auditConfirmPublicity,
} from "@/api/energyconsumption/earlyWarning";
import { deepClone, replaceDigit } from "@/utils/index";
export default {
  name: "earlyWarning",
  dicts: ["warnning_level", "warning_instruct_type"],
  data() {
    return {
      deleteInstructIds: [],
      publishTime: "",
      expirationTime: "",
      contentIds: [],
      versionId: null,
      showSearch: true, // 显示搜索条件
      // 查询参数
      queryParams: {
        level: null,
        version: null,
      },
      versionsArr: [], // 版本号集合
      // 表格数据
      listform: {
        level: "",
        list: [],
      },
      listRules: {
        level: [
          {
            required: true,
            message: "预警等级不能为空",
            trigger: ["blur", "change"],
          },
        ],
        instructType: [
          {
            required: true,
            message: "能源种类不能为空",
            trigger: ["blur", "change"],
          },
        ],
        templateId: [
          {
            required: true,
            message: "预警规则描述不能为空",
            trigger: ["blur", "change"],
          },
          { validator: this.validContent },
        ],
      },
      inputFlage: true, // 输入框钩子
      editFlage: true, // 编辑钩子
      addFlage: true, // 新增版本钩子
      publishStatus: 0, // 发布钩子
      /* ......................数据交互...................... */
      addVersionname: null,
      // 规格配置单行数据结构
      rowObj: {
        instructVoTemplates: [], // 能源种类
        numList: [], // 实物量单位
        params: [], // 标准煤系数
        templateId: "",
        type: "",
      },
    };
  },
  created() {
    this.initializeGet();
  },
  methods: {
    /* 自定义校验 */
    validContent(rule, value, callback) {
      const list = this.listform.list.map((item) => {
        if (item.level && item.level && item.templateId) {
          item =
            String(item.level) +
            String(item.instructType) +
            String(item.templateId);
          return item;
        }
      });
      let arr = list.filter(function (s) {
        return s && s.trim();
      });
      if (new Set(arr).size !== arr.length) {
        callback("预警规则描述不能重复,请修改");
      } else {
        callback();
      }
    },
    // 输入框输入只能是2位小数
    replaceDigitDeal(val, digit, index, key, idx) {
      this.listform.list[index][key][idx].x = replaceDigit(val, digit);
    },
    async initializeGet(version) {
      const aa = await this.getVersions(version);
      if (aa) {
        const bb = await this.handleQuery();
      }
    },
    /* 查询版本对应配置列表 */
    getList() {
      this.$store.commit("app/updateApiCount", "add");
      list(this.queryParams)
        .then((res) => {
          this.$store.commit("app/updateApiCount");
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          this.listform.list = res.data.energyEarlyWarningInstructVoList.map(
            (item) => {
              let arr = [];
              for (let i = 0; i < item.params.length; i++) {
                arr.push({ x: item.params[i] });
              }
              item.numList = arr;
              return item;
            }
          );
          // 发布按钮状态
          this.expirationTime = res.data.expirationTime;
          this.publishTime = res.data.publishTime;
          this.publishStatus = res.data.status;
          this.versionId = res.data.id;
        })
        .catch((err) => {
          this.$store.commit("app/updateApiCount");
          // this.$message.error("系统错误,请联系管理员!300302");
        });
    },
    /* 请求版本号的集合 */
    getVersions(version) {
      return new Promise((resolve, reject) => {
        listversion()
          .then((res) => {
            if (res.code === 700) {
              this.$message.warning(res.msg);
              return false;
            }
            if (res.code === 200) {
              this.versionsArr = res.data;
              if (this.versionsArr.length > 0) {
                if (version == undefined) {
                  this.queryParams.version = this.versionsArr[0];
                } else {
                  if (version == "add") {
                    // 新增
                    this.versionsArr.map((item) => {
                      if (item.version == this.addVersionname) {
                        this.queryParams.version = item;
                      }
                    });
                  } else {
                    // 修改
                  }
                }
                resolve(true);
              }
            }
          })
          .catch((error) => {
            // this.$message.error("系统错误,请联系管理员!300301");
          });
      });
    },
    getVal(val, data, index) {
      const info = data.find((item) => item.templateId === val);
      let arr = [];
      if (this.listform.list[index].level === 1) {
        for (let i = 0; i < info.paramNums; i++) {
          if (info.paramNums === 1) {
            arr.push({ x: info.defaultValueMax ?? info.defaultValueMin });
          } else {
            if (i === 0) {
              arr.push({ x: info.defaultValueMin });
            } else {
              arr.push({ x: info.defaultValueMax });
            }
          }
        }
      } else {
        for (let i = 0; i < info.paramNums; i++) {
          arr.push({ x: "" });
        }
      }
      this.$set(this.listform.list[index], "numList", arr);
    },
    changeRules(index) {
      if (this.listform.list[index].templateId) {
        this.$refs.tableForm.validateField(`list.${index}.templateId`);
      }
    },
    getContent(val, index) {
      const that = this;
      instructList({ instructType: val })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          that.$set(that.listform.list[index], "instructVoTemplates", res.data);
          that.$set(that.listform.list[index], "numList", []);
          that.$set(that.listform.list[index], "templateId", "");
        })
        .catch(() => {
          // this.$message.error("系统错误,请联系管理员!300303");
        });
    },
    //! 搜索
    handleQuery() {
      if (!this.queryParams.version) {
        this.$message.warning("搜索必须先确定版本号");
        return false;
      }
      // 搜索请求
      this.getList();
    },
    //! 重置按钮
    handleresetQuery() {
      this.resetQuery();
      this.initializeGet();
    },
    //? 重置搜索表单
    resetQuery() {
      this.resetForm("queryForm");
      this.versionId = null;
      this.queryParams = {
        level: null,
        version: null,
      };
    },
    //? 清空表格
    restTable() {
      this.$refs["tableForm"].resetFields();
      this.listform.list = [];
      this.deleteInstructIds = [];
    },
    //? 条件搜索框和输入框可否输入
    changeFlage(status) {
      this.inputFlage = status;
      this.showSearch = status;
    },
    //* 编辑
    handleEdit() {
      let that = this;
      // 首先判断版本号有无
      if (this.editFlage) {
        // 编辑时打开编辑权限 按钮变保存
        this.editFlage = !this.editFlage;
        this.changeFlage(false);
      } else {
        this.$refs["tableForm"].validate((throu) => {
          if (throu) {
            if (this.listform.list.length == 0) {
              this.$message.error("标准煤折算系数版本最起码需要一条配置");
            } else {
              this.listform.list = this.listform.list.map((item) => {
                let arr = [];
                for (let i = 0; i < item.numList.length; i++) {
                  if (item.numList[i].x) {
                    arr.push(item.numList[i].x);
                  }
                }
                item.params = arr;
                return item;
              });
              for (let i = 0; i < this.listform.list.length; i++) {
                if (
                  this.listform.list[i].params.length <
                  this.listform.list[i].numList.length
                ) {
                  this.$message.warning(`第${i + 1}行规则预警值不能为空`);
                  return false;
                }
              }
              this.$confirm("确认编辑该版本吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.requestEdit();
                })
                .catch(() => {
                  this.deleteInstructIds = [];
                  this.$message({
                    type: "info",
                    message: "已取消",
                  });
                });
            }
          }
        });
      }
    },
    // todo 请求编辑接口
    requestEdit() {
      const data = this.listform.list;
      addWarningEmanage({
        data,
        version: this.queryParams.version,
        deleteInstructIds: this.deleteInstructIds,
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          } else if (res.code === 200) {
            this.$message({
              type: "success",
              message: "编辑成功!",
            });
            this.editFlage = true;
            this.changeFlage(true);

            // 重新请求版本号的集合(根据ID请求编辑后的该版本)
            this.initializeGet(this.queryParams.version);
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!20020");
        });
    },
    //* 新增
    handleAdd() {
      if (this.addFlage) {
        // 新增版本时打开新增权限 清空查询条件 清空表格所有数据并打开新增表格行数的按钮
        this.resetQuery();
        this.restTable();
        // 默认添加一行 数据结构等接口
        this.listform.list.push(deepClone(this.rowObj));
        this.addFlage = !this.addFlage;
        this.changeFlage(false);
      } else {
        // 确认新增
        if (this.listform.list.length == 0) {
          this.$message.warning("标准煤折算系数版本最起码需要一条配置");
        } else {
          this.$refs["tableForm"].validate((throu) => {
            // 通过tableForm校验
            if (throu) {
              this.listform.list = this.listform.list.map((item) => {
                let arr = [];
                for (let i = 0; i < item.numList.length; i++) {
                  if (item.numList[i].x) {
                    arr.push(item.numList[i].x);
                  }
                }
                item.params = arr;
                return item;
              });
              for (let i = 0; i < this.listform.list.length; i++) {
                if (
                  this.listform.list[i].params.length <
                  this.listform.list[i].numList.length
                ) {
                  this.$message.warning(`第${i + 1}行规则预警值不能为空`);
                  return false;
                }
              }
              this.$confirm("确认添加该版本吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              })
                .then(() => {
                  this.requestAdd();
                })
                .catch(() => {
                  this.$message({
                    type: "info",
                    message: "已取消",
                  });
                });
            }
          });
        }
      }
    },
    // todo 请求新增版本接口
    requestAdd() {
      const data = this.listform.list;
      addWarningEmanage({
        data,
      })
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          }
          if (res.code === 200) {
            this.$message({
              type: "success",
              message: "添加成功!",
            });
            this.addFlage = true;
            this.changeFlage(true);
            // 重新请求版本号的集合(根据ID请求新增后的该版本)
            this.addVersionname = null;
            this.addVersionname = this.queryParams.version;
            this.initializeGet();
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300304");
        });
    },
    //* 取消新增或编辑
    handleCancel() {
      this.restTable();
      this.changeFlage(true);
      // 新增时候取消重新获取版本号默认渲染第一个
      if (!this.addFlage) {
        this.resetQuery();
        this.addFlage = true;
        this.initializeGet();
      }
      // 编辑的时候渲染当前的版本号
      if (!this.editFlage) {
        this.editFlage = true;
        this.initializeGet(this.queryParams.version);
      }
    },
    //* 发布
    handlePublish() {
      this.$confirm("确认发布该版本吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.publishRequest();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    // todo 发布请求
    publishRequest() {
      auditGoPublish(this.versionId)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          } else if (res.code === 200) {
            this.$message({
              type: "success",
              message: "发布成功!",
            });
            this.initializeGet(this.queryParams.version);
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300306");
        });
    },

    //公示
    handleConfirm() {
      this.$confirm("确认公示该版本吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.confirm();
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消",
          });
        });
    },
    confirm() {
      auditConfirmPublicity(this.versionId)
        .then((res) => {
          if (res.code === 700) {
            this.$message.warning(res.msg);
            return false;
          } else if (res.code === 200) {
            this.$message({
              type: "success",
              message: "操作成功!",
            });
            this.initializeGet(this.queryParams.version);
          }
        })
        .catch((err) => {
          // this.$message.error("系统错误,请联系管理员!300305");
        });
    },
    // 表格新增一行
    addRow() {
      // 新增版本时打开新增权限才能新增行
      if (!this.addFlage || !this.editFlage) {
        this.listform.list.push(deepClone(this.rowObj));
      }
    },
    /* ....................表格相关..................... */
    // 删除
    handleDelete(row) {
      if (row.id) {
        this.deleteInstructIds.push(row.id);
      }
      const index = this.listform.list.indexOf(row);
      this.listform.list.splice(index, 1);
    },
  },
};
</script>

<style scoped lang="scss">
.energyCoal {
  ::v-deep .el-card__header {
    border-bottom: none;
  }
  // .type-tag {
  //   transform: translateY(-14px);
  // }
  // .cell-span {
  //   // transform: translateY(40px);
  //   transform: translateY(-14px);
  //   // text-align: center;
  // }
  .cell-center {
    // transform: translateY(10px);
    margin-top: 12px;
  }
  .midcol {
    height: 40px;
    position: relative;
    .el-form-item {
      // margin: 9px 0 0 0px;
    }
    .sapn-input {
      width: 250px;
      /*1. 先强制一行内显示文本*/
      white-space: nowrap;
      /*2. 超出的部分隐藏*/
      overflow: hidden;
      /*3. 文字用省略号替代超出的部分*/
      text-overflow: ellipsis;
    }
  }
  .midbutton {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .table-area {
    margin-top: 20px;
    position: relative;
    .addbutton-area {
      position: absolute;
      right: 0px;
      top: -35px;
    }
  }
}
.button-area-ex {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
.table-title {
  font-size: 20px;
  font-family: PingFangSC-Semibold, PingFang SC;
  font-weight: 600;
  color: #333333;
  line-height: 30px;
  margin: -10px 0 10px 0;
  span {
    opacity: 0.8;
  }
}
</style>
